#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include<dirent.h>
#include<string.h>

/*
 *
-rw-rw-r-- 347 2024-12-14 10:12 buffer.c
drwxrwxr-x 4096 2024-12-19 21:24 .
-rw-rw-r-- 390 2024-12-18 21:33 1.txt
-rw-rw-r-- 542 2024-12-14 10:23 f_open.c
-rw-rw-r-- 1661 2024-12-19 21:24 stat_test.c
-rw-rw-r-- 331 2024-12-15 13:9 ffush.c
-rw-rw-r-- 970 2024-12-18 21:34 wsystime_fileIO.c
-rw-rw-r-- 561 2024-12-18 22:30 readdir.c
-rw-rw-r-- 77 2024-12-18 20:14 test.txt
-rw-rw-r-- 9 2024-12-18 7:32 ftest.txt
-rw-rw-r-- 72 2024-12-15 11:52 1.bin
-rw-rw-r-- 1236 2024-12-19 7:55 stat.c
-rw-rw-r-- 574 2024-12-14 18:42 fgetc_fputc.c
-rw-rw-r-- 442 2024-12-14 19:22 fputs_puts.c
-rw-rw-r-- 564 2024-12-18 7:35 fprintf_fscanf.c
-rw-rw-r-- 606 2024-12-14 19:8 fgets_gets.c
-rw-rw-r-- 526 2024-12-15 13:24 fseek_frewind_ftell.c
-rw-rw-r-- 849 2024-12-17 22:42 wsystime.c
-rw-rw-r-- 241 2024-12-19 7:21 chmod.c
dr--r--r-- 4096 2024-12-19 7:21 temp
-rw-rw-r-- 377 2024-12-16 7:49 sprintf_sscanf.c
drwxrwxr-x 4096 2024-12-14 8:33 ..
-rw-rw-r-- 1145 2024-12-18 20:17 readwrite.c
-rwxrwxr-x 16408 2024-12-19 21:24 a.out
-rw-rw-r-- 476 2024-12-18 19:48 open.c
-rw-rw-r-- 1415 2024-12-15 11:52 fread_fwrite.c

 */

int main(){
	struct stat buf;
	int ret;
	
	//打开目录
	char dest[30] = "/home/linux/CProject/IO/";
	DIR * dir = opendir(dest);
	struct dirent * dt;
	if(dir == NULL){
		perror("opendir");
		return 0;
	}

	//读取目录
	while((dt = readdir(dir)) != NULL){
		char target[50]; 
		strcpy(target, dest);
		strcat(target, dt->d_name);
		ret = stat(target, &buf);
		if(ret < 0){
			perror("stat");
			return 0;
		}

		//判断文件类型 借助st_mode
		if(S_ISREG(buf.st_mode)){
			//常规文件
			printf("-");
		}
		if(S_ISDIR(buf.st_mode)){
			//目录文件
			printf("d");
		}
		if(S_ISCHR(buf.st_mode)){
			//字符设备
			printf("c");
		}
		if(S_ISBLK(buf.st_mode)){
			//块设备
			printf("b");
		}
		if(S_ISFIFO(buf.st_mode)){
			//管道文件
			printf("p");
		}
		if(S_ISSOCK(buf.st_mode)){
			//套接字文件
			printf("s");
		}

		//判断文件权限 借助st_mode
		for(int i = 8; i >= 0; i--){
			if(buf.st_mode & (1<<i)){
				switch(i % 3){
					case 2:
						printf("r");
						break;
					case 1:
						printf("w");
						break;
					case 0:
						printf("x");
						break;
				}
			}else{
				printf("-");
			}
		}

		//打印文件大小
		printf(" %d", (int)buf.st_size);

		//打印最后一次修改时间
		struct tm * t = localtime(&buf.st_ctime);
		printf(" %d-%d-%d %d:%d", t->tm_year+1900, t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min);

		//打印文件名
		printf(" %s\n", dt->d_name);
	}


	//关闭目录
	closedir(dir);	
}

